package com.chii.colorization.ui.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.chii.colorization.R;
import com.chii.colorization.R2;
import com.chii.colorization.utils.SPUtil;
import com.chii.colorization.utils.TimeUtils;
import com.chii.colorization.utils.connes.MyUrl;
import com.chii.colorization.utils.connes.OkHttpUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PayActivity extends AppCompatActivity {
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    @BindView(R2.id.pay_pay)
    Button B_Pay;
    @BindView(R2.id.pay_username)
    TextView TV_username;
    @BindView(R2.id.pay_order_no)
    TextView TV_orderNo;
    @BindView(R2.id.pay_payment_amount)
    TextView TV_paymentAmount;
    @BindView(R2.id.pay_order_state)
    TextView TV_orderState;
    @BindView(R2.id.pay_order_created_time)
    TextView TV_orderCreatedTime;
    @BindView(R2.id.pay_refresh)
    Button payRefresh;
    private Handler mHandler;
    private JSONObject orderObject;
    private String saveUsername;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //todo 沙箱
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        ButterKnife.bind(this);
        //初始化返回按键
        initAction();
        initHandler();
        initData();
    }

    private void initAction() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }


    private void initData() {
        saveUsername = (String) SPUtil.get(PayActivity.this, "username", "");
        Intent intent = getIntent();  //获取intent传递
        String data = intent.getStringExtra("data");//获取值
        if ("get".equals(data)) {
            getOrder();
        } else {
            creatOrder();
        }

    }

    private void initView() {
        //用户名
        TV_username.setText(saveUsername);
        //订单号
        TV_orderNo.setText(orderObject.getString("orderNo"));
        //付款金额
        String paymentAmount = "￥ " + orderObject.getString("paymentAmount");
        TV_paymentAmount.setText(paymentAmount);
        //订单状态
        String orderState = orderObject.getBoolean("paymentState") ? "已经付款" : "未付款";
        //已经付款不显示付款按键
        if (!orderObject.getBoolean("paymentState")) {
            B_Pay.setVisibility(View.VISIBLE);
        }
        TV_orderState.setText(orderState);

        //订单创建时间
        String orderCreatedTime = orderObject.getString("createdAt");
        String time = TimeUtils.dealDateFormat(orderCreatedTime);
        TV_orderCreatedTime.setText(time);

        //刷新vip状态
        Boolean vip = (Boolean) SPUtil.get(PayActivity.this, "vip", Boolean.FALSE);
        if (!vip && orderObject.getBoolean("paymentState")) {
            Intent intent = new Intent();
            setResult(Activity.RESULT_OK, intent);
            finish();
        }

    }

    @OnClick({R.id.pay_pay,R.id.pay_refresh})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pay_pay:
                //已付款
                if (orderObject.getBoolean("paymentState")) {
                    showAlert(PayActivity.this, "你已经付款过");
                    return;
                }
                //出现刷新按键
                payRefresh.setVisibility(View.VISIBLE);

                OkHttpUtil okHttpUtil = OkHttpUtil.getInstance(this);
                HashMap<String, String> map = new HashMap<>();
                map.put("orderNo", orderObject.getString("orderNo"));
                map.put("orderDescription", "会员购买");

                okHttpUtil.post(MyUrl.ali_pay, map, new OkHttpUtil.MyCallback() {
                    @Override
                    public void success(String s) {
                        PayTask alipay = new PayTask(PayActivity.this);
                        JSONObject jsonObject = JSON.parseObject(s);

                        Map<String, String> result = alipay.payV2(jsonObject.getString("data"), true);

                        Message msg = new Message();
                        msg.what = Integer.parseInt(result.get("resultStatus"));
                        msg.obj = result.get("result");
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void failed(IOException e) {
                        Message message = new Message();
                        message.what = 0;
                        mHandler.sendMessage(message);
                    }
                });
                break;
            case R.id.pay_refresh:
                getOrder();
                break;
            default:
        }

    }

    void payReturn(JSONObject pay_response) {
        OkHttpUtil okHttpUtil = OkHttpUtil.getInstance(PayActivity.this);
        HashMap<String, String> map = new HashMap<>();
        map.put("orderNo", pay_response.getString("out_trade_no"));
        okHttpUtil.post(MyUrl.ali_pay_return, map, new OkHttpUtil.MyCallback() {
            @Override
            public void success(String s) {
                JSONObject jsonObject = JSON.parseObject(s);
                if (jsonObject.getInteger("code") == 200) {
                    Message msg = new Message();
                    msg.what = 9001;
                    mHandler.sendMessage(msg);
                }

            }

            @Override
            public void failed(IOException e) {
            }
        });
    }

    private void initHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case 8999:
                        orderObject = JSON.parseObject((String) msg.obj);
                        initView();
                        break;
                    case 9000:
                        JSONObject result = JSONObject.parseObject((String) msg.obj);
                        JSONObject pay_response = result.getJSONObject("alipay_trade_app_pay_response");
                        //todo 回传支付信息，正式删除用支付宝异步
                        payReturn(pay_response);

                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        showAlert(PayActivity.this, getString(R.string.pay_success));

                        break;
                    case 9001:
                        Intent intent = new Intent();
                        setResult(Activity.RESULT_OK, intent);
                        finish();

                        break;
                    default:
                        showAlert(PayActivity.this, getString(R.string.pay_failed));


                }
                return false;

            }
        });
    }

    private static void showAlert(Context ctx, String info) {
        new AlertDialog.Builder(ctx)
                .setMessage(info)
                .setPositiveButton("xxx", null)
                .setOnDismissListener(null)
                .show();
    }


    private void getOrder() {
        //获取订单
        OkHttpUtil okHttpUtil = OkHttpUtil.getInstance(this);
        HashMap<String, String> map = new HashMap<>();
        map.put("username", saveUsername);
        okHttpUtil.get(MyUrl.order, map, new OkHttpUtil.MyCallback() {
            @Override
            public void success(String s) {
                JSONObject jsonObject = JSON.parseObject(s);
                JSONArray data = jsonObject.getJSONArray("data");
                if (data != null && data.size() != 0) {
                    Message msg = new Message();
                    msg.what = 8999;
                    msg.obj = data.getString(data.size()-1);
                    mHandler.sendMessage(msg);
                }
            }

            @Override
            public void failed(IOException e) {
                Message message = new Message();
                message.what = 0;
                mHandler.sendMessage(message);
            }
        });
    }

    private void creatOrder() {
        // 生成订单
        OkHttpUtil okHttpUtil = OkHttpUtil.getInstance(this);
        HashMap<String, String> map = new HashMap<>();
        map.put("username", saveUsername);
        okHttpUtil.post(MyUrl.order, map, new OkHttpUtil.MyCallback() {
            @Override
            public void success(String s) {
                JSONObject jsonObject = JSON.parseObject(s);
                Message msg = new Message();
                msg.what = 8999;
                msg.obj = jsonObject.getString("data");
                mHandler.sendMessage(msg);
            }

            @Override
            public void failed(IOException e) {
                Message message = new Message();
                message.what = 0;
                mHandler.sendMessage(message);
            }
        });
    }
}
